import datetime
import random

from flask import current_app
from flask_migrate import Migrate,MigrateCommand
from flask_script import Manager
from info import create_app,db,models


# 调用方法获取app
from info.models import User

app = create_app("develop")

# 配置数据库迁移
manager = Manager(app)
Migrate(app,db)
manager.add_command("db",MigrateCommand)


@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')
def create_super_user(username, password):
    # 创建管理员对象
    admin = User()

    # 设置管理员属性
    admin.mobile = username
    admin.nick_name = username
    admin.password = password
    admin.last_login = datetime.now()
    admin.is_admin = True

    # 添加多数据库
    try:
        # 开启上下文
        with app.app_context():
            db.session.add(admin)
            db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建管理员失败"

    print("管理员创建成功")


# 添加测试数据
def add_test_users():
    # 获取当前时间
    now = datetime.datetime.now()

    # 定义容器
    user_list = []

    # 遍历创建多个用户对象
    for num in range(10, 1000):
        # 创建用户对象
        user = User()

        # 设置属性
        user.mobile = "138%08d" % num
        user.nick_name = "138%08d" % num
        user.password_hash = "pbkdf2:sha256:50000$jd4sB2bw$6f79afc790f4ee1340e6fc914a4c06bce2634999632be848d7c73e2abb67f507"
        user.is_admin = False
        # 一个月以内用户登录的时间，相当于创建时间
        user.last_login = now - datetime.timedelta(seconds=random.randint(0,3600*24*31))

        # 添加到列表中
        user_list.append(user)

    # 添加对象到数据库中
    try:
        with app.app_context():
            db.session.add_all(user_list)
            db.session.commit()
    except Exception as e:
        # 由于current_app没在上下文内部，会报错
        # current_app.logger.error(e)
        return "创建失败"

    print("创建添加成功")


if __name__ == '__main__':
    # add_test_users()
    manager.run()
